package com.cql.framework.async.factory;

import com.cql.common.constant.FoodCircleConstant;
import com.cql.common.core.DO.LoginInfoDO;
import com.cql.common.utils.LogUtils;
import com.cql.common.utils.ServletUtils;
import com.cql.common.utils.ip.AddressUtils;
import com.cql.common.utils.ip.IpUtils;
import com.cql.common.utils.spring.SpringUtils;
import com.cql.service.business.LoginInfoService;
import eu.bitwalker.useragentutils.UserAgent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Date;
import java.util.TimerTask;

/**
 * @author cql
 */
public class AsyncFactory {

    private static final Logger logger = LoggerFactory.getLogger(AsyncFactory.class);

    /**
     * 记录登录信息
     *
     * @param account 用户名
     * @param status  状态
     * @param message 消息
     * @param args    列表
     * @return 任务task
     */
    public static TimerTask recordLoginInfo(final String account, final String status, final String message,
                                            final Object... args) {
        final UserAgent userAgent = UserAgent.parseUserAgentString(ServletUtils.getRequest().getHeader("User-Agent"));
        final String ip = IpUtils.getIpAddr(ServletUtils.getRequest());
        return new TimerTask() {
            @Override
            public void run() {
                String address = AddressUtils.getRealAddressByIP(ip);
                StringBuilder s = new StringBuilder();
                s.append(LogUtils.getBlock(ip));
                s.append(address);
                s.append(LogUtils.getBlock(account));
                s.append(LogUtils.getBlock(status));
                s.append(LogUtils.getBlock(message));
                // 打印信息到日志
                logger.info(s.toString(), args);
                // 获取客户端操作系统
                String os = userAgent.getOperatingSystem().getName();
                // 获取客户端浏览器
                String browser = userAgent.getBrowser().getName();
                // 封装对象
                LoginInfoDO logininfor = new LoginInfoDO();
                logininfor.setAccount(account);
                logininfor.setIpaddr(ip);
                logininfor.setLoginLocation(address);
                logininfor.setBrowser(browser);
                logininfor.setOs(os);
                logininfor.setMsg(message);
                logininfor.setLoginTime(new Date());
                // 日志状态
                if (FoodCircleConstant.LOGIN_SUCCESS.equals(status) || FoodCircleConstant.LOGOUT.equals(status)) {
                    logininfor.setStatus(FoodCircleConstant.SUCCESS);
                } else if (FoodCircleConstant.LOGIN_FAIL.equals(status)) {
                    logininfor.setStatus(FoodCircleConstant.FAIL);
                }
                // 插入数据
                SpringUtils.getBean(LoginInfoService.class).insertLoginInfo(logininfor);
            }
        };
    }

}
